<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1000px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <!-- 奖项名称 -->
      <el-form-item :label="t('template.fields.awardsName')" prop="awardsName">
        <el-input
          v-model="formData.awardsName"
          :placeholder="t('common.inputTextPlaceholder') + t('template.fields.awardsName')"
          :maxlength="40"
          show-word-limit
        />
      </el-form-item>
      <!-- 荣誉类型 -->
      <el-form-item :label="t('template.fields.honorType')" prop="honorType">
        <el-select
          v-model="formData.honorType"
          :placeholder="t('common.selectTextPlaceholder') + t('template.fields.honorType')"
          clearable
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.HONOR_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- 个人/集体 -->
      <el-form-item :label="t('template.fields.teamHonor')" prop="teamHonor">
        <el-select
          v-model="formData.teamHonor"
          :placeholder="t('common.selectTextPlaceholder') + t('template.fields.teamHonor')"
          clearable
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.HONOR_TEAM_HONOR)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('template.fields.onlineApply')" prop="onlineApply">
        <el-radio-group v-model="formData.onlineApply">
          <el-radio :value="true">{{ t('common.yes') }}</el-radio>
          <el-radio :value="false">{{ t('common.no') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="t('template.fields.qualificationReview')" prop="qualificationReview">
        <el-radio-group v-model="formData.qualificationReview">
          <el-radio :value="true">{{ t('common.yes') }}</el-radio>
          <el-radio :value="false">{{ t('common.no') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="t('template.fields.preliminaryEvaluation')"
        prop="preliminaryEvaluation"
      >
        <el-radio-group
          v-model="formData.preliminaryEvaluation"
          @change="onPreliminaryEvaluationChanged"
        >
          <el-radio :value="true">{{ t('common.yes') }}</el-radio>
          <el-radio :value="false">{{ t('common.no') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="t('template.fields.differenceSelection')" prop="differenceSelection">
        <el-radio-group v-model="formData.differenceSelection">
          <el-radio :value="true">{{ t('common.yes') }}</el-radio>
          <el-radio :value="false">{{ t('common.no') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="t('template.fields.conditionJson')">
        <el-checkbox
          v-for="(item, index) in conditionArray"
          :key="index"
          v-model="item.value"
          :label="item.label"
        />
      </el-form-item>
      <el-form-item :label="t('template.fields.awardsType')" prop="awardsType">
        <el-select
          v-model="formData.awardsType"
          :placeholder="t('common.selectTextPlaceholder') + t('template.fields.awardsType')"
        >
          <el-option label="通用奖项" :value="0" />
          <el-option label="师昌绪奖学金" :value="1" />
        </el-select>
      </el-form-item>
      <!-- 通用设置 -->
      <el-tabs v-if="formData.awardsType === 0" v-model="activeRuleName" type="border-card">
        <el-tab-pane
          v-if="formData.preliminaryEvaluation"
          :label="t('template.initialRules')"
          name="initial"
        >
          <StageRules
            ref="initialStageRulesRef"
            :is-initial="true"
            :template-data="formData"
            :rules-data="initialStageRules"
          />
        </el-tab-pane>
        <el-tab-pane :label="t('template.finalRules')" name="final">
          <StageRules
            ref="finalStageRulesRef"
            :is-initial="false"
            :template-data="formData"
            :rules-data="finalStageRules"
          />
        </el-tab-pane>
      </el-tabs>
      <!-- 师昌绪专属设置 -->
      <ScxRulesSetting v-if="formData.awardsType === 1" ref="scxFormRef" />
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { TemplateApi, TemplateVO } from '@/api/awards/template'
import { FormRules } from 'element-plus'
import ScxRulesSetting from './components/ScxRulesSetting.vue'
import StageRules from '@/views/awards/template/components/general/StageRules.vue'
import { getStrDictOptions } from '@/utils/dict'
import { DICT_TYPE } from '@/utils/dict'

/** 奖项 表单 */
defineOptions({ name: 'TemplateForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const defaultJson =
  '[{"key": "ustc", "label": "中国科大学籍", "value": false},{"key": "atSchoolOrAfterAugust", "label": "在校生或毕业时间(离所时间)大于去年八月份", "value": false}, {"key": "atSchoolOrJustGraduate", "label": "在校标识为在校或在校标识为离校且毕结业时间为评选年度1月1日及以后", "value": false}, {"key": "allDay", "label": "学习方式: 全日制", "value": false}, {"key": "nonDirectional", "label": "培养方式: 非定向", "value": false}, {"key": "nonInternational", "label": "学生类别为不含留学硕士&留学博士", "value": false}, {"key": "notAtSchool", "label": "在校标识: 离校", "value": false}, {"key": "graduate", "label": "学籍状态: 毕业", "value": false}, {"key": "phd", "label": "学位: 博士", "value": false}, {"key": "graduateDateRange", "label": "学位日期范围", "value": false}, {"key": "secondGrade", "label": "二年级及以上研究生", "value": false}]'
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<any>({
  id: undefined,
  awardsName: undefined,
  onlineApply: undefined,
  conditionJson: defaultJson,
  qualificationReview: undefined,
  differenceSelection: undefined,
  preliminaryEvaluation: undefined,
  awardsType: undefined,
  honorType: undefined,
  teamHonor: undefined,
  remark: undefined
})

const formRules = reactive<FormRules>({
  awardsName: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('template.fields.awardsName'),
      trigger: 'blur'
    }
  ],
  honorType: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('template.fields.honorType'),
      trigger: 'change'
    }
  ],
  teamHonor: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('template.fields.teamHonor'),
      trigger: 'change'
    }
  ],
  onlineApply: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('template.fields.onlineApply'),
      trigger: 'blur'
    }
  ],
  qualificationReview: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('template.fields.qualificationReview'),
      trigger: 'blur'
    }
  ],
  preliminaryEvaluation: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('template.fields.preliminaryEvaluation'),
      trigger: 'blur'
    }
  ],
  differenceSelection: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('template.fields.differenceSelection'),
      trigger: 'blur'
    }
  ],
  awardsType: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('template.fields.awardsType'),
      trigger: 'change'
    }
  ]
})

const formRef = ref() // 表单 Ref
const scxFormRef = ref() // 师昌绪专属规则设置表单 Ref
const initialStageRulesRef = ref() // 通用初评规则设置 表单 Ref
const finalStageRulesRef = ref() // 通用终评规则设置 表单 Ref
const activeRuleName = ref('initial') // 当前选中的规则设置 Tab 名称
const initialStageRules = ref() // 通用初评规则设置
const finalStageRules = ref() // 通用终评规则设置
const conditionArray = ref<any[]>([])

// 是否初评单选回调
const onPreliminaryEvaluationChanged = async (value: boolean) => {
  if (value) {
    activeRuleName.value = 'initial'
    await initialStageRulesRef.value?.initData()
  } else {
    activeRuleName.value = 'final'
    await finalStageRulesRef.value?.initData()
  }
}

// 处理初评终评规则回显
const handleStageRules = async () => {
  const { templateRuleList } = formData.value as unknown as TemplateVO
  if (!templateRuleList?.length) return
  templateRuleList.forEach((rule) => {
    if (rule.judgeStage === '1') {
      initialStageRules.value = rule
    } else if (rule.judgeStage === '2') {
      finalStageRules.value = rule
    }
  })
}

/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TemplateApi.getTemplate(id)
      if (formData.value.awardsType === 0) {
        activeRuleName.value = formData.value.preliminaryEvaluation ? 'initial' : 'final'
        await handleStageRules()
      }
      await nextTick()
      if (formData.value.awardsType === 0) {
        // 通用的
        initialStageRulesRef.value?.initData()
        finalStageRulesRef.value?.initData()
      }
      if (formData.value.awardsType === 1) {
        // scx的 还需要读取amount表 模版的ID就是scxAmount的ID
        scxFormRef.value?.fetchData(id)
      }
    } finally {
      formLoading.value = false
    }
  }
  conditionArray.value = JSON.parse(formData.value.conditionJson || defaultJson)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

// 处理规则提交 不处理异常 向上抛出
const submitRules = async (templateId: string) => {
  const data = formData.value as unknown as TemplateVO
  // 通用规则设置
  if (data.awardsType === 0) {
    // 初评 如果有则提交
    if (data.preliminaryEvaluation) {
      await initialStageRulesRef.value.submit(templateId)
    }
    // 终评
    await finalStageRulesRef.value.submit(templateId)
  }
  if (data.awardsType === 1) {
    // scx的 还需要写入amount表
    await scxFormRef.value.submit(templateId)
  }
}

const submitForm = async () => {
  const data = formData.value as unknown as TemplateVO
  // 校验表单
  try {
    await formRef.value.validate()
    if (data.awardsType === 0) {
      if (data.preliminaryEvaluation) {
        await initialStageRulesRef.value.validate()
      }
      await finalStageRulesRef.value.validate()
    }
    if (data.awardsType === 1) {
      await scxFormRef.value.validate()
    }
  } catch {
    message.error(t('template.submitTips'))
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    data.conditionJson = JSON.stringify(conditionArray.value)
    if (formType.value === 'create') {
      const templateId = await TemplateApi.createTemplate(data)
      await submitRules(templateId)
      message.success(t('common.createSuccess'))
    } else {
      await TemplateApi.updateTemplate(data)
      await submitRules(data.id)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    awardsName: undefined,
    onlineApply: undefined,
    conditionJson: defaultJson,
    qualificationReview: undefined,
    differenceSelection: undefined,
    preliminaryEvaluation: undefined,
    awardsType: undefined,
    honorType: undefined,
    teamHonor: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()

  scxFormRef.value?.resetForm()
  initialStageRulesRef.value?.resetForm()
  finalStageRulesRef.value?.resetForm()

  activeRuleName.value = 'initial'
  initialStageRules.value = undefined
  finalStageRules.value = undefined
}
</script>
